package com.itcm.skymail.auth.controller;

import com.alibaba.fastjson.JSON;
import com.itcm.common.constant.AuthServerConstant;
import com.itcm.common.vo.ResultMemberVo;
import com.itcm.skymail.auth.feign.MemberFeignService;
import com.itcm.skymail.auth.vo.WeiboAccessVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;

/**
 * 描述: 处理社交登录请求
 *
 * @author cm_fighting
 * @create 2020-11-10 12:08 下午
 */
@Controller
@Slf4j
public class Oauth2Controller {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(String code, HttpSession session) throws InvocationTargetException, IllegalAccessException {
        log.info("weibo授权返回code:{}", code);
        // 换取accessToken
        String url = "https://api.weibo.com/oauth2/access_token";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", "338493581");
        map.add("client_secret", "89df3ebaf0b72390ed2b72e83c4414d5");
        map.add("grant_type", "authorization_code");
        map.add("redirect_uri", "http://auth.skymail.com/oauth2.0/weibo/success");
        map.add("code", code);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, null);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        System.out.println(response);
        System.out.println(response.getBody());
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.is2xxSuccessful()) {
            // 成功
            WeiboAccessVo weiboAccessVo = JSON.parseObject(response.getBody(), WeiboAccessVo.class);
            String accessToken = weiboAccessVo.getAccessToken();
            System.out.println(accessToken);
            // 判断是否第一次使用微博登录 是：自动注册 否：登录成功  -- skymail-member
            ResultMemberVo member = memberFeignService.weiboLogin(weiboAccessVo);
            if (member != null) {
                // 成功
                log.info("登录成功，用户信息：{}", member.toString());
                session.setAttribute(AuthServerConstant.LOGIN_USER, member);
                return "redirect:http://skymail.com";
            } else {
                return "redirect:http://auth.skymail.com/login.html";
            }
        } else {
            // 失败
            return "redirect:http://auth.skymail.com/login.html";
        }
    }
}
